package casa.depesos.app.com.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.common.base.task.SilentTask;
import com.common.base.task.TaskEngine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Locale;

import casa.depesos.app.com.adapter.BankListAdapter;
import casa.depesos.app.com.databinding.ActivityBankListBinding;
import casa.depesos.app.com.http.data.Bank;

public class BankListActivity extends BaseActivity {

    ActivityBankListBinding binding;
    BankListAdapter adapter = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBankListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.top.title.setText("Bancos admitidos");
        binding.top.back.setOnClickListener(v -> finish());
        binding.list.setLayoutManager(new LinearLayoutManager(this));

        ArrayList<Bank> list = getIntent().getParcelableArrayListExtra("banks");
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                sort(list);
            }
        });
    }

    private void sort(ArrayList<Bank> list) {
        Collections.sort(list, new Comparator<Bank>() {
            @Override
            public int compare(Bank o1, Bank o2) {
                return o1.name.compareTo(o2.name);
            }
        });
        ArrayList tmp = new ArrayList();
        String last = String.valueOf(list.get(0).name.charAt(0)).toUpperCase(Locale.US);
        tmp.add(last);
        for (Bank b : list) {
            String s = String.valueOf(b.name.charAt(0)).toUpperCase(Locale.US);
            if (s.equals(last)) {
                tmp.add(b);
            } else {
                tmp.add(s);
                tmp.add(b);
                last = s;
            }
        }
        h.post(() -> {
            adapter = new BankListAdapter(tmp, BankListActivity.this);
            binding.list.setAdapter(adapter);
        });
    }

    public void select(Bank item) {
        Intent i = new Intent();
        i.putExtra("bank", item);
        setResult(RESULT_OK, i);
        finish();
    }
}
